<html>
<head>

<title>Groovy Goodness: Loop Through Date and Calendar Ranges</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Loop Through Date and Calendar Ranges</h3>

<div class="post">
<p>Groovy already adds a lot of extra methods to the <code>Date</code> and <code>Calendar</code> classes. And since Groovy 2.2 we can use the <code>upto()</code> method and loop over a begin date up to another date. We pass a closure that is executed for each day. We can also iterate back using the <code>downto()</code> method.</p><pre class="brush:groovy">// We can loop from today
// to nextWeek and invoke a closure for each day.
def today = new Date().clearTime()
def nextWeek = today + 7

today.upto(nextWeek) {
    // Print day of the week.
    println it.format('EEEE')
}

println()

nextweek.downto(today) {
    prinltn it.format('EEEE')
}
</pre><p>When we run the code we get the following output:</p><pre class="brush:plain;light:true">Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Monday

Monday
Sunday
Saturday
Friday
Thursday
Wednesday
Tuesday
Monday
</pre><p>In the next sample we use the <code>upto()</code> method on the <code>Calendar</code> class:</p><pre class="brush:groovy">// upto() also works on Calendar objects.
def to = Calendar.instance
to.set(year: 2013, month: Calendar.NOVEMBER, date: 18)

def from = Calendar.instance
from.set(year: 2013, month: Calendar.NOVEMBER, date: 13)

from.upto(to) {
    if (it[Calendar.DATE] % 2 == 0) {
        print 'Even'
    } else {
        print 'Odd'
    }
    println ' date'
}
</pre><p>We get the following output:</p><pre class="brush:plain;light:true">Odd date
Even date
Odd date
Even date
Odd date
Even date
</pre><p>Code written with Groovy 2.2.</p
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>